package v1

import (
	"net/http"
	"toy-car/pkg/e"
	"toy-car/pkg/util"

	"github.com/gin-gonic/gin"
)

// @Tags excel
// @Summary 导入Excel文件
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce  application/json
// @Param file formData file true "导入Excel文件"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"导入成功"}"
// @Router /excel/importExcel [post]
func ExcelImport(c *gin.Context) {
	_, header, err := c.Request.FormFile("file")

	data := make(map[string]interface{})
	code := e.SUCCESS

	// todo 比对删除自己，返回错误
	if err != nil {
		code = e.ERROR
	} else {
		_ = c.SaveUploadedFile(header, "./upload"+"ExcelImport.xlsx")
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMSG(code),
		"data": data,
	})
}

// @Tags excel
// @Summary 下载模板
// @Security ApiKeyAuth
// @accept multipart/form-data
// @Produce  application/json
// @Param fileName query string true "模板名称"
// @Success 200
// @Router /excel/downloadTemplate [get]
func DownloadTemplate(c *gin.Context) {
	fileName := c.Query("fileName")
	filePath := "./upload" + fileName
	ok, err := util.PathExists(filePath)
	if !ok || err != nil {
		c.JSON(http.StatusNotFound, gin.H{})
		return
	}
	c.Writer.Header().Add("success", "true")
	c.File(filePath)
}
